package uk.co.revisual.domino.proxies {
	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;
	import org.puremvc.as3.multicore.utilities.statemachine.State;
	
	import uk.co.revisual.domino.core.FSMHistory;
	import uk.co.revisual.domino.consts.DominoConsts;


	/**
	 * @private
	 */
	 
	public class FSMHistoryProxy extends Proxy implements FSMHistory
	{

		
		
		private var _historyLength:int = 5;
		
		private var _transitionDuple:StateDuple;
		private var _isInTransition:Boolean;
				
		public function FSMHistoryProxy(  ):void{
			
			super( DominoConsts.PROXY_NAMES.FSM_HISTORY_PROXY, [] );
			_transitionDuple = new StateDuple("initial", null );
			
		}
		
		public function get historyLength():int{
			return _historyLength;
		}
		
		public function set historyLength( value:int ):void{
			_historyLength = value;
			if(states.length > _historyLength)setData(states.slice( 0, _historyLength ));
		}
		
		public function get isInTransition():Boolean{
			return _isInTransition;
		}
		
		public function get currentState():State{
			return getStateAt(0);
		}
		
		public function get previousState():State{
			return getStateAt(1);
		}
		
		public function get currentReferringAction():String{
			if( _transitionDuple == null )return getReferringActionAt(0);
			else return _transitionDuple.action; 
		}
		
		public function getStateAt( index:int ):State{
			var duple:StateDuple = StateDuple( states[ index ] );
			if( duple == null ) return null;
			return duple.target;
		}
		
		public function getReferringActionAt( index:int ):String{
			var duple:StateDuple = states[ index ] as StateDuple;
			if( duple == null ) return null;
			return duple.action;
		}
		
		public function setTransition( action:String ):void{
			_isInTransition = true;
			_transitionDuple = new StateDuple( action, null );
		}
		
		public function confirmTransitionToNewState( state:State ):void{
			_isInTransition = false;
			_transitionDuple.target = state;
			states.unshift( _transitionDuple );
			_transitionDuple = null;
			if(states.length > _historyLength)states.pop();
		}
		
		public function cancelTransition():void{
			_isInTransition = false;
			_transitionDuple = null;
		}
		
		
		
		private function get states():Array{
			return data as Array;
		}
		
		
		

	}
	
}
	import org.puremvc.as3.multicore.utilities.statemachine.State;
	

internal class StateDuple{
	internal var action:String;
	internal var target:State;
	public function StateDuple( action:String, target:State ){
		this.action = action;
		this.target = target;
	}
}

